package com.lidx.back.statistics.controller.admin;

import com.google.gson.GsonBuilder;
import com.lidx.back.statistics.entity.SysUser;
import com.lidx.back.statistics.service.ISysUserService;
import com.lidx.back.statistics.utils.UserUtils;
import com.lidx.back.statistics.websocket.Message;
import com.lidx.back.statistics.websocket.MyWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@Controller
public class ChatController {
	@Autowired
	MyWebSocketHandler handler;
	
	@Autowired
	ISysUserService sysUserService;
	
	@RequestMapping("/onlineusers")
	@ResponseBody
	public Set<String> onlineusers(HttpSession session, HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin","*");
		Map<Integer, WebSocketSession> map=MyWebSocketHandler.userSocketSessionMap;
		Set<Integer> set=map.keySet();
		Iterator<Integer> it = set.iterator();
		Set<String> nameset=new HashSet<String>();
		while(it.hasNext()){
			Integer entry = it.next();
			String name=sysUserService.getUserById(entry).getName();
			String user = UserUtils.getUser().getName();
			if(!user.equals(name))
				nameset.add(name);
		}
		return nameset;
	}
	
	// 发布系统广播（群发）
		@ResponseBody
		@RequestMapping(value = "broadcast", method = RequestMethod.POST)
		public void broadcast(@RequestParam("text") String text,HttpServletResponse response) throws IOException {
			response.setHeader("Access-Control-Allow-Origin","*");
			Message msg = new Message();
			msg.setDate(new Date());
			msg.setFrom(-1);//-1表示系统广播
			msg.setFromName("系统广播");
			msg.setTo(0);
			msg.setText(text);
			handler.broadcast(new TextMessage(new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create().toJson(msg)));
		}
		
	@RequestMapping(value = "getuid",method = RequestMethod.POST)
	@ResponseBody
	public SysUser getuid(@RequestParam("username")String username,HttpServletResponse response){
		response.setHeader("Access-Control-Allow-Origin","*");
		int a=sysUserService.getUserByName(username).getId();
		SysUser u=new SysUser();
		u.setId(a);
		return u;
	}

	@RequestMapping(value = "admin/chatroom",method = RequestMethod.GET)
	public ModelAndView goChatRoom(){
		return new ModelAndView("chat/list");
	}
}
